//
//  IM_Service+Read.m
//  SportSocial
//
//  Created by yull on 14/12/10.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "IM_Service+Read.h"
#import "Parser.h"
#import "Server.pb.h"
#import "BaseIMNet.h"

@implementation IM_Service (Read)

- (void)parseBuffData
{
    while (YES) {
        
        if ([self.buffData length] < IM_PACKET_HEAD_LENGTH) {
            return;
        }
        
        NSUInteger loc = 0;
        UInt32 length = [Parser parseDataToUInt32:self.buffData loc:&loc];
        
        UInt32 bodyLength = (UInt32)[self.buffData length] - IM_PACKET_HEAD_LENGTH;
        if (bodyLength < length) {
            NSLog(@"包未接收完整");
            return;
        }
        
        NSData *bodyData = [self.buffData subdataWithRange:NSMakeRange(IM_PACKET_HEAD_LENGTH, length)];
        
        UInt32 packetLength = IM_PACKET_HEAD_LENGTH + length;
        
        NSRange packRange = NSMakeRange(packetLength, self.buffData.length - packetLength);
        self.buffData = [NSMutableData dataWithData:[self.buffData subdataWithRange:packRange]];
        
        [self filterReceiveData:bodyData];
    }
}

- (void)filterReceiveData:(NSData *)recData
{
    if (recData.length <= 2) {
        return;
    }
    
    NSInteger pId = [Parser parseDataToUInt16:[recData subdataWithRange:NSMakeRange(0, 2)]];
    NSLog(@"收到消息pid:%d",pId);
    
    for (BaseIMNet *baseImNet in self.arrayNet) {
        for (NSNumber *pid in baseImNet.arrayPid) {
            if (pid.integerValue == pId) {
                [baseImNet handlePacketWithPid:pId recvData:[recData subdataWithRange:NSMakeRange(2, recData.length - 2)]];
                break;
            }
        }
    }
}
@end
